/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class BSTIterator {
    //使用O(h)，保留二叉树的左子树
    vector <TreeNode *> d;
public:
    BSTIterator(TreeNode* root) {
        dfsLeft(root);
    }
    int next() {
        TreeNode * root = d.back();
        d.pop_back();
        int ans = root->val;
        root = root->right;
        dfsLeft(root);
        return ans;
    }
    void dfsLeft(TreeNode * root) {
         while (root) {
             d.push_back(root);
             root = root->left;
         }
     }
    bool hasNext() {
        return !d.empty();
    }
};

/**
 * Your BSTIterator object will be instantiated and called as such:
 * BSTIterator* obj = new BSTIterator(root);
 * int param_1 = obj->next();
 * bool param_2 = obj->hasNext();
 */